package view.controller;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import utils.Connect;
import utils.User;
import view.AddNewFriend;
import view.MainWindow;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
/**
 * @author
 */
public class AddNewFriendController implements Initializable {
    public Button findButton;
    public TextField idField;
    public Pane backPane;
    public ImageView headImage;
    public Button addButton;
    public Label userLabel;
    User user=null;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        AddNewFriend.getAddNewFriend().setBackPane(backPane);
        AddNewFriend.getAddNewFriend().setHeadImage(headImage);
        AddNewFriend.getAddNewFriend().setUserLabel(userLabel);
        backPane.setVisible(false);

    }
    public void findButtonClicked(MouseEvent mouseEvent) throws IOException {
        AddNewFriend.getAddNewFriend().setChooseUser(null);
        String account = idField.getText();
        if(account.equals(MainWindow.getMainWindow().getUser().getAccount())){
            backPane.setVisible(false);
            Alert alert = new Alert(Alert.AlertType.INFORMATION, "你不能添加自己", new ButtonType("确认", ButtonBar.ButtonData.YES));
            alert.setTitle("提示");
            alert.show();
            return;
        }
        for(User x: MainWindowController.friends){
            if(account.equals(x.getAccount())){
                backPane.setVisible(false);
                Alert alert = new Alert(Alert.AlertType.INFORMATION, "已经添加为好友", new ButtonType("确认", ButtonBar.ButtonData.YES));
                alert.setTitle("提示");
                alert.show();
                return;
            }
        }

        Connect connect=Connect.getConnect();
        connect.getHeadByAccount(account);
        connect.getUserByAccount(account,0);

    }

    public void addButtonClicked(MouseEvent mouseEvent) throws IOException {
        Connect connect=Connect.getConnect();
        connect.addFriend(MainWindow.getMainWindow().getUser(),AddNewFriend.getAddNewFriend().getChooseUser());
        Alert alert = new Alert(Alert.AlertType.INFORMATION, "请求已发送", new ButtonType("确认", ButtonBar.ButtonData.YES));
        alert.setTitle("提示");
        alert.show();
        backPane.setVisible(false);
        idField.clear();
    }

    @FXML
    public void idFieldKeyPressed(KeyEvent event) throws IOException {
        if (event.getCode() == KeyCode.ENTER) {
            this.findButtonClicked(null);
        }
    }
}
